package com.foursome.shouguang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.foursome.shouguang.common.R;
import com.foursome.shouguang.entity.Stock;
import com.foursome.shouguang.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/stock")
public class StockController {


    @Autowired
    private StockService stockService;

    
    @GetMapping("/top4")
    @CrossOrigin(allowCredentials = "true",allowedHeaders = "*", originPatterns ="*")
    public  R<List<Stock>> getTop4(){
        QueryWrapper<Stock> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("stock_birthday").last("LIMIT 4");
        List<Stock> top4List = stockService.list(wrapper);
        return R.success(top4List);
    }

    @GetMapping("/season")
    @CrossOrigin(allowCredentials = "true",allowedHeaders = "*", originPatterns ="*")
    public  R<Page> season(int page, int pageSize, String name,String season){
        log.info("page = {},pageSize = {},name = {},season = {}" ,page,pageSize,name,season);
        // 构造分页构造器
        Page<Stock> pageInfo = new Page<>(page, pageSize);
        // 构造查询条件构造器
        QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
        // 添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), "stock_name", name);
        // 添加product表的过滤条件
        queryWrapper.inSql("product_id", "select product_id from product where product_season like '%" + season + "%'");
        // 添加排序条件
        queryWrapper.orderByAsc("stock_id");
        // 调用mybatis-plus的分页查询方法
        Page<Stock> resultPage = stockService.page(pageInfo, queryWrapper);
        // 返回结果
        return R.success(resultPage);
    }

    @GetMapping("/{id}")
    @CrossOrigin(allowCredentials = "true",allowedHeaders = "*", originPatterns ="*")
    public R<Stock> getById(@PathVariable Long id){
        log.info("根据id查询库存信息...");
        Stock stock = stockService.getById(id);
        if(stock != null){
            return R.success(stock);
        }
        return R.error("没有查询到对应库存信息");
    }
}
